package zmee.bid.formplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.AbstractFormDataModel;
import kd.bos.entity.datamodel.TableValueSetter;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.events.BeforeClosedEvent;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.scm.pds.common.expertfilter.expertfilter.ExpertFilterUtils;
import kd.scm.pds.common.expertfilter.expertfilter.IExpertFilter;
import kd.scm.pds.common.expertfilter.schemefilter.ExpertSchemeContext;
import kd.scm.pds.common.expertfilter.schemefilter.ExpertSchemeUtils;
import kd.scm.pds.common.expertfilter.schemefilter.IExpertScheme;
import kd.scm.pds.common.expertfilter.selecttool.ExpertContext;
import kd.scm.pds.common.expertfilter.selecttool.PdsExpertRecordLog;
import kd.scm.pds.common.expertfilter.selecttool.PdsExpertSelectHelper;
import kd.scm.pds.common.expertfilter.selecttool.PdsExpertSelectUtils;
import kd.scm.pds.common.extfilter.ExtFilterFactory;
import kd.scm.pds.common.extfilter.ExtFilterUtils;
import kd.scm.pds.common.extfilter.FilterGridUtils;
import kd.scm.pds.common.extfilter.PdsQFilterHelper;
import kd.scm.pds.common.extplugin.ExtPluginContext;
import kd.scm.pds.common.extplugin.ExtPluginFactory;
import kd.scm.pds.common.util.ExtParameterUtils;
import kd.scm.pds.common.util.OpenFormUtils;
import kd.scm.pds.common.util.PdsCommonUtils;
import kd.scm.pds.common.util.RandomUtils;

import java.util.*;
import java.util.stream.Collectors;

public class PdsSelectexpertList extends AbstractListPlugin {

    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        PdsExpertSelectUtils.setQueryConditionVisible(this.getView(), Boolean.FALSE);
        ExpertContext context = this.getExpertContext();
        PdsExpertSelectUtils.initModel(context);
        PdsExpertSelectUtils.initContext(context);
        if (isAutoQueryAndShow(context)) {
            this.queryAndShowExpert(context, true);
        } else {
            this.queryAndShowExpert(context, false);
        }

    }

    public void beforeDoOperation(BeforeDoOperationEventArgs evt) {
        super.beforeDoOperation(evt);
        String opKey = ((AbstractOperate)evt.getSource()).getOperateKey();
        ExpertContext context = null;
        QFilter qfilters = null;
        String entityName = null;
        byte var7 = -1;
        switch(opKey.hashCode()) {
            case -1289163222:
                if (opKey.equals("expert")) {
                    var7 = 2;
                }
                break;
            case 951117504:
                if (opKey.equals("confirm")) {
                    var7 = 0;
                }
                break;
            case 1085444827:
                if (opKey.equals("refresh")) {
                    var7 = 1;
                }
                break;
            case 2030362628:
                if (opKey.equals("logquery")) {
                    var7 = 3;
                }
        }

        switch(var7) {
            case 0:
                context = this.getExpertContext();
                PdsExpertSelectUtils.returnData(context);
                evt.setCancel(!context.isSucced());
                break;
            case 1:
                PdsExpertSelectUtils.setQueryConditionVisible(this.getView(), Boolean.FALSE);
                context = this.getExpertContext();
                PdsExpertSelectUtils.initContext(context);
                this.queryAndShowExpert(context, true);
                break;
            case 2:
                entityName = "src_expert";
                qfilters = QFilter.fromSerializedString(this.getView().getPageCache().get(entityName));
                OpenFormUtils.openListPage(this.getView(), entityName, ShowType.MainNewTabPage, (Map)null, qfilters, (CloseCallBack)null);
                break;
            case 3:
                qfilters = new QFilter("project", "=", this.getModel().getDataEntity().getLong("project.id"));
                OpenFormUtils.openListPage(this.getView(), "pds_expselectlog", ShowType.MainNewTabPage, (Map)null, qfilters, (CloseCallBack)null);
        }

    }

    public void beforeClosed(BeforeClosedEvent evt) {
        super.beforeClosed(evt);
        ExtPluginContext context = new ExtPluginContext();
        context.setView(this.getView());
        ExtPluginFactory.executeExtplugin(PdsExpertRecordLog.class.getSimpleName(), context, true);
    }

    private void getExpertIds(ExpertContext context) {
       getExpertQFilter(this.getView(), context);
        if (!context.isEmpty() && context.getUltimateQFilter() != null) {
            if (this.isAdd()) {
                context.getUltimateQFilter().and("id", "not in", this.getPreExpertIds());
            }

            this.getModel().setValue("qfilter_tag", context.getUltimateQFilter().toSerializedString());
            DynamicObjectCollection rows = QueryServiceHelper.query("src_expert", "id", context.getUltimateQFilter().toArray());
            if (null != rows && rows.size() > 0) {
                Set<Long> expertIds = (Set)rows.stream().map((e) -> {
                    return e.getLong("id");
                }).collect(Collectors.toSet());
                expertIds = RandomUtils.getRandomElement(expertIds, context.getRandomCount());
                context.setExpertUserIds(expertIds);
            }
        }

    }

    private void queryAndShowExpert(ExpertContext context, boolean isShowExpert) {
        this.getExpertIds(context);
        if (isShowExpert) {
            this.showExpert(context);
            this.showCondition(context);
        }

    }

    private void showExpert(ExpertContext context) {
        Set<Long> expertIds = context.getExpertUserIds();
        if (expertIds.size() > 0) {
            this.addTurns(expertIds.size());
        } else if (this.isAdd()) {
            return;
        }

        String selects = "id";
        AbstractFormDataModel model = (AbstractFormDataModel)this.getModel();
        if (!this.isAdd()) {
            model.deleteEntryData("entryentity");
        }

        int i = 0;
        TableValueSetter ts = new TableValueSetter(new String[0]);
        DynamicObject[] objs = BusinessDataServiceHelper.load("src_expert", selects, new QFilter[]{new QFilter("id", "in", expertIds)});
        DynamicObject[] var8 = objs;
        int var9 = objs.length;

        for(int var10 = 0; var10 < var9; ++var10) {
            DynamicObject obj = var8[var10];
            ts.set("isinvite", Boolean.TRUE, i);
            ts.set("expert", obj.getLong("id"), i);
            ts.set("entryentityturns", this.getTurns(), i);
            ++i;
        }

        model.batchCreateNewEntryRow("entryentity", ts);
    }

    private ExpertContext getExpertContext() {
        ExpertContext context = PdsExpertSelectUtils.getContextInstance();
        context.setView(this.getView());
        FormShowParameter formShowPara = this.getView().getFormShowParameter();
        context.setParamMap(formShowPara.getCustomParams());
        return context;
    }

    private boolean isAdd() {
        return this.getModel().getDataEntity().getBoolean("isadd");
    }

    private Set<Long> getPreExpertIds() {
        DynamicObjectCollection rows = this.getView().getModel().getEntryEntity("entryentity");
        return (Set)rows.stream().map((e) -> {
            return e.getLong("expert.id");
        }).collect(Collectors.toSet());
    }

    private int getTurns() {
        return this.getModel().getDataEntity().getInt("turns");
    }

    private void addTurns(int number) {
        this.getModel().setValue("turns", this.getTurns() + 1);
        this.getModel().setValue("number", number);
    }

    private int getNumber() {
        return this.getModel().getDataEntity().getInt("number");
    }

    private void showCondition(ExpertContext context) {
        if (null != context.getExpertUserIds() && context.getExpertUserIds().size() != 0) {
            StringBuilder qfilterSb = new StringBuilder();
            StringBuilder descriptionSb = new StringBuilder();
            StringBuilder prefixSb = new StringBuilder();
            prefixSb.append(ResManager.loadKDString("抽取轮次(", "PdsExpertSelectHelper_0", "scm-pds-common", new Object[0])).append(this.getTurns()).append(ResManager.loadKDString(")，抽取数(", "PdsExpertSelectHelper_1", "scm-pds-common", new Object[0])).append(this.getNumber()).append(")：");
            if (this.isAdd() && PdsCommonUtils.object2String(this.getModel().getValue("condition"), "").length() > 0) {
                qfilterSb.append(this.getModel().getValue("condition")).append("\n");
                descriptionSb.append(this.getModel().getValue("description")).append("\n");
            }

            qfilterSb.append(prefixSb).append(context.getAllQFilter());
            descriptionSb.append(prefixSb).append(context.getAllDescription());
            this.getModel().setValue("qfilter", context.getUltimateQFilter());
            this.getModel().setValue("condition", qfilterSb);
            this.getModel().setValue("description", descriptionSb);
        }
    }

    public static boolean isAutoQueryAndShow(ExpertContext context) {
        QFilter schemeQfilter = getSchemeFilter(context.getView());
        if (null == schemeQfilter) {
            return false;
        } else {
            String orderBy = "basedata.number,matchfield desc,number";
            DynamicObjectCollection rows = QueryServiceHelper.query("src_expertscheme", "id,number,matchfield,basedata.number,basedata.name,fieldid", schemeQfilter.toArray(), orderBy);
            if (null != rows && rows.size() != 0) {
                Iterator var4 = rows.iterator();

                DynamicObject row;
                do {
                    if (!var4.hasNext()) {
                        return false;
                    }

                    row = (DynamicObject)var4.next();
                } while(!ExtParameterUtils.convertToBoolen(ExtParameterUtils.getExtParameterValueById("src_expertscheme", row.getLong("id"), "isautoquery", false, context.getProjectId())));

                return true;
            } else {
                return false;
            }
        }
    }

    public static QFilter getSchemeFilter(IFormView view) {
        ExpertSchemeContext context = new ExpertSchemeContext();
        context.setView(view);
        getFilterParameter(context);
        Map<String, Object> qfilterMap = FilterGridUtils.getQFilter("pds_extfilter", IExpertScheme.class.getSimpleName());
        context.setQfilter((QFilter)qfilterMap.get("qfilter"));
        Object description = qfilterMap.get("description");
        if (!StringUtils.isBlank(description)) {
            context.setDescription(new StringBuilder(description.toString()));
        }

        List<IExpertScheme> extFilters = ExtFilterFactory.getInstance().getExtFilterInstance("pds_extfilter", IExpertScheme.class.getSimpleName());
        if (null != extFilters && extFilters.size() > 0) {
            Iterator var5 = extFilters.iterator();

            while(var5.hasNext()) {
                IExpertScheme extFilter = (IExpertScheme)var5.next();
                extFilter.buildQFilter(context);
            }
        }

        return context.getQfilter();
    }

    public static void getFilterParameter(ExpertSchemeContext context) {
        context.setProjectObj(getProjectObj(context.getView()));
    }

    public static void getFilterParameter(ExpertContext context) {
        context.setProjectObj(getProjectObj(context.getView()));
    }


    public static DynamicObject getProjectObj(IFormView view) {
        IFormView componentView = view.getParentView();
        if (Objects.isNull(componentView)) {
            return null;
        } else {
            IFormView projectView;
            String name = componentView.getModel().getDataEntityType().getName();
            if("src_bidopen".equals(name)) {
                DynamicObject sourcetype = (DynamicObject) componentView.getModel().getValue("sourcetype");
                String number = sourcetype.getString("number");
                switch (number) {
                    case "C010406":
                    case "C010418":
                        projectView = componentView;
                        break;
                    default:
                        projectView = componentView.getParentView();
                        break;
                }
            }else{
                projectView = componentView.getParentView();
            }
            if (Objects.isNull(projectView)) {
                return null;
            } else if ("src_project".equals(projectView.getEntityId())) {
                return projectView.getModel().getDataEntity();
            } else if ("src_bidchange".equals(projectView.getEntityId())) {
                return projectView.getModel().getDataEntity().getDynamicObject("project");
            } else {
                return "src_addsupplier".equals(componentView.getEntityId()) ? componentView.getModel().getDataEntity().getDynamicObject("project") : projectView.getModel().getDataEntity();
            }
        }
    }

    public static void getExpertQFilter(IFormView view, ExpertContext context) {
        QFilter schemeQfilter = getSchemeFilter(view);
        if (null != schemeQfilter) {
            String orderBy = "basedata.number,matchfield desc,number";
            DynamicObjectCollection rows = QueryServiceHelper.query("src_expertscheme", "id,number,matchfield,basedata.number,basedata.name,fieldid", schemeQfilter.toArray(), orderBy);
            if (null != rows && rows.size() != 0) {
                Map<String, List<DynamicObject>> basedataMap = (Map)rows.stream().collect(Collectors.groupingBy((e) -> {
                    return e.getString("basedata.number");
                }));
                context.setView(view);
                context.setEmpty(false);
                getFilterParameter(context);
                Object[] basedataIds = new Object[basedataMap.size()];
                int index = 0;
                Iterator var8 = basedataMap.entrySet().iterator();

                while(var8.hasNext()) {
                    Map.Entry<String, List<DynamicObject>> entry = (Map.Entry)var8.next();
                    basedataIds[index++] = ((DynamicObject)((List)entry.getValue()).get(0)).getLong("id");
                    setQueryConditionVisible(context, (DynamicObject)((List)entry.getValue()).get(0));
                    getExpertQFilterByScheme(context, (DynamicObject)((List)entry.getValue()).get(0));
                    if (context.isEmpty()) {
                    }
                }

                view.getModel().setValue("scheme", basedataIds);
            }
        }
    }

    private static void setQueryConditionVisible(ExpertContext context, DynamicObject schemeObj) {
        String baseDataType = schemeObj.getString("basedata.number");
        context.setBaseDataType(baseDataType);
        String baseDataName = schemeObj.getString("basedata.name");
        context.setBaseDataName(baseDataName);
        PdsExpertSelectUtils.setQueryConditionVisible(context.getView(), baseDataType, Boolean.TRUE);
        ExtFilterUtils.setProperiesVisibleByScheme(schemeObj.getLong("id"), "src_expertscheme", context.getView(), Boolean.TRUE);
    }

    private static void getExpertQFilterByScheme(ExpertContext context, DynamicObject schemeObj) {
        long schemeId = schemeObj.getLong("id");
        schemeObj = BusinessDataServiceHelper.loadSingle(schemeId, "src_expertscheme");
        Map<String, Object> qfilterMap = FilterGridUtils.getQFilter("src_expertscheme", schemeId);
        context.setQfilter((QFilter)qfilterMap.get("qfilter"));
        context.setDescription(new StringBuilder(qfilterMap.get("description").toString()));
        ExtFilterUtils.getFieldMatchQFilter(context, schemeObj, context.getView().getModel().getDataEntity());
        List<IExpertFilter> extFilters = ExtFilterFactory.getInstance().getExtFilterInstance("src_expertscheme", schemeId);
        if (null != extFilters && extFilters.size() > 0) {
            Iterator var6 = extFilters.iterator();

            while(var6.hasNext()) {
                IExpertFilter extFilter = (IExpertFilter)var6.next();
                extFilter.buildQFilter(context);
            }
        }

        buildExpertQFilter(context, schemeObj);
        PdsQFilterHelper.buildQFilterDescription(context);
    }

    private static void buildExpertQFilter(ExpertContext context, DynamicObject schemeObj) {
        QFilter qfilter = context.getQfilter();
        if (qfilter != null) {
            context.getView().getPageCache().put(context.getBaseDataType(), qfilter.toSerializedString());
            String fieldName = schemeObj.getString("fieldid");
            if (StringUtils.isBlank(fieldName)) {
                fieldName = "expert";
            }

            String fieldId = fieldName + "." + "id";
            if ("src_expert".equals(context.getBaseDataType())) {
                linkExpertQFilter(context, qfilter);
            } else {
                DynamicObjectCollection rows = QueryServiceHelper.query(context.getBaseDataType(), fieldId, qfilter.toArray());
                if (rows != null && rows.size() != 0) {
                    Set<Long> expertIds = (Set)rows.stream().map((e) -> {
                        return e.getLong(fieldId);
                    }).collect(Collectors.toSet());
                    QFilter expertQfilter = new QFilter("id", "in", expertIds);
                    linkExpertQFilter(context, expertQfilter);
                } else {
                    context.setEmpty(true);
                }

            }
        }
    }

    private static void linkExpertQFilter(ExpertContext context, QFilter qfilter) {
        if (null != qfilter) {
            if (context.getUltimateQFilter() == null) {
                context.setUltimateQFilter(qfilter);
            } else {
                context.setUltimateQFilter(context.getUltimateQFilter().and(qfilter));
            }

        }
    }
}
